package com.hnas.sys.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hnas.core.dao.PageBean;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.exception.EntityNotFoundException;
import com.hnas.core.exception.ParamEmptyException;
import com.hnas.core.util.StringUtil;
import com.hnas.sys.dao.AuthorityDAO;
import com.hnas.sys.dao.ManagerDAO;
import com.hnas.sys.domain.ResourceStatus;
import com.hnas.sys.orm.Authority;
import com.hnas.sys.orm.Manager;
import com.hnas.sys.service.system.criteria.DTOSearchManager;
import com.hnas.sys.service.system.dto.DTOManager;
import com.hnas.sys.service.system.mapper.ManagerMapper;

@Component("managerService")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class ManagerService implements IManagerService {
	@Autowired
	private ManagerDAO managerDAO;
	
	
	
	public DTOPagedList<DTOManager> search(DTOSearchManager con) {
		// TODO Auto-generated method stub
//		return null;
		PageBean<Manager> page = new PageBean<Manager>();
		page.setPageNo(con.getPageNo());
		page.setPageSize(con.getPageSize());
		page.setTotalCount(con.getTotalCount());
		StringBuffer sb = new StringBuffer();
		List<String> paras = new ArrayList<String>();
		int j=1;
		sb.append(" and t.statusStr='VALID'");
		if (StringUtil.isNotEmpty(con.getName())) {
			sb.append(" and t.name like ?" + j++);
			paras.add("%"+con.getName().trim()+"%");
		}
		if (StringUtil.isNotEmpty(con.getAccount())) {
			sb.append(" and t.account like ?" + j++);
			paras.add("%"+con.getAccount().trim()+"%");
		}

		if (sb.length() > 0) {
			sb.delete(0, 5);
			sb.insert(0, " from Manager t where ");
		} else {
			sb.append(" from Manager t");
		}
		page.setQuery(sb.toString());
		page.setQueryCount("select count(t.id) " + sb);
//		page.setQuery(sb.insert(" from Manager t".length(), " join fetch t.product ").toString());
		managerDAO.queryByPage(page, paras.toArray());
		DTOPagedList<DTOManager> pageList = new DTOPagedList<DTOManager>();
		pageList.setPageNo(page.getPageNo());
		pageList.setPageSize(page.getPageSize());
		pageList.setTotalCount(page.getTotalCount());
		List<DTOManager> ls = new ArrayList<DTOManager>();
		for (Manager or : page.getList()) {
			DTOManager dto = new DTOManager();
			dto = ManagerMapper.getInstance().mapToValue(or);
			
			ls.add(dto);
		}
		pageList.setList(ls);
		return pageList;
	}

	public DTOManager get(long id) {
		// TODO Auto-generated method stub
//		return null;
		Manager vo = this.managerDAO.find(id);
		return ManagerMapper.getInstance().mapToValueIncAuth(vo);
	}
	@Autowired
	private AuthorityDAO authorityDAO;
	public long save(DTOManager dto) throws EntityNotFoundException,
			ParamEmptyException {
		// TODO Auto-generated method stub
//		return 0;
		Manager vo = this.getManager(dto);
		
		if (null==vo){
			vo = new Manager();
		}else{
		}
		BeanUtils.copyProperties(dto, vo, new String[]{"id","valid","password"});
		vo.setStatus(ResourceStatus.VALID);
		//密码不相等时才修改
		if(dto.getPassword()!=""){
			String password = new Md5PasswordEncoder().encodePassword(dto.getPassword(), vo.getAccount());
			//System.out.println("password:"+password);
			vo.setPassword(password);
		}
		Map<Long, Authority> map = new HashMap<Long, Authority>();
		for (Authority at : vo.getAuthoritys()) {
			map.put(at.getId(), at);
		}
		vo.getAuthoritys().clear();
		Set<Long> set = new HashSet<Long>();
		if (null!=dto.getAuths())
		for(long id:dto.getAuths()){
			if (set.contains(id))
				continue;//重复
			Authority au = map.get(id);
			if (null!=au){
				
			}else{
				au = this.authorityDAO.find(id);
				if (null==au)
					throw new EntityNotFoundException(""+id);
			}
			vo.getAuthoritys().add(au);
			set.add(au.getId());
		}
		
		if (vo.getId()==0){
			this.managerDAO.persist(vo);
		}else{
			this.managerDAO.merge(vo);
		}
		return vo.getId();
	}
	public void savePass(DTOManager dto) throws EntityNotFoundException,ParamEmptyException {
		Manager vo = this.managerDAO.find(dto.getId());
		if(null!=vo){
			String password = new Md5PasswordEncoder().encodePassword(dto.getPassword(), vo.getAccount());
			vo.setPassword(password);
			this.managerDAO.merge(vo);
		}
    }
	private Manager getManager(DTOManager dto){
		if (dto.getId()>0)
			return  this.managerDAO.find(dto.getId());
		if (StringUtil.isNotEmpty(dto.getAccount())){
			String query = "from Manager t where t.account=?1";
			List<Manager> ls = this.managerDAO.findByQuery(query, dto.getAccount());
			if (ls.size() > 0){
				return ls.get(0);
			}
//			return this.managerDAO.getManagerByName(dto.getManagerName());
		}
		return null;
	}
	public void disable(long id) {
		// TODO Auto-generated method stub
		Manager vo = this.managerDAO.find(id);
		vo.setStatus(ResourceStatus.INVALID);
		this.managerDAO.merge(vo);
	}

}
